const db=wx.cloud.database();
const _=db.command;

//添加物品到捐助人的信息
export const addProjectToDonor =async(_openid , project , amount ,date) =>{
  try {
    var id =project._id;
    var price =project.price;
    console.log(id)
    
    const result = await db.collection("donor").field({ projects: true }).get();
    console.log(result.data[0].projects);
    const projectsData = result.data[0].projects;

    let foundMatch = false; // 标志变量

    projectsData.forEach((item,index) => {
      const itemId = item._id;
      //console.log(itemId); 
      if(itemId===id){
        console.log(itemId); 
        console.log(item);
        item.amount+=amount;
        db.collection("donor").doc("f18e14fa6543438604a4c12e76abaa0f").update({
          data: {
            ['projects.' + index]: item,
          },
        })
        wx.cloud.callFunction({
          name:"updateProjectWithQuantity",
          data:{
            project: project,
            credit: Math.round(amount * price),
            donatedMoney : Math.round(amount * price)
          }
        }).then(res =>{
          console.log(res);
        })
        foundMatch = true; // 设置标志为true
      }
      
    });

    if (foundMatch) {
      return; 
    }

    delete project.quantity;
    project.amount = amount;  
    project.date = date;
    console.log(project);
    var res1 = await db.collection("donor").where({
      _openid: _openid,
    }).update({
      data: {
        projects: _.push(project),
      },
    });

    wx.cloud.callFunction({
      name:"updateProjectWithQuantity",
      data:{
        project:project,
        credit: Math.round(amount * price),
        donatedMoney : Math.round(amount * price)
      }
    }).then(res =>{
      console.log(res);
    })
  } catch (error) {
    console.error("add error: ", error);
  }




}